import { Login, SendSMS } from '@/api'
import Bg from '@/assets/bg-1.jpg'
import classNames from 'classnames'
import { useState } from 'react'
import { Button, Checkbox, Divider, Form, hooks, Input, Toast } from 'react-vant'
import { history, useMutation } from 'umi'

export default function LoginPage() {
  const [form] = Form.useForm()
  const [agree, setAgree] = useState<boolean>(false)

  // #登录
  const { mutate: login, isLoading: isLogging } = useMutation({
    mutationFn: Login,
    onSuccess({ token }) {
      localStorage.token = token
      history.replace('/')
    },
  })

  const { current, start: startCutDown } = hooks.useCountDown({
    // 倒计时 24 小时
    time: 60 * 1000,
  })

  function onFinish(values: any) {
    if (!agree)
      return Toast.fail('请先同意协议')
    login({
      ...values,
    })
  }

  // #发送验证码
  const { mutate: sendSMS, isLoading: isSending } = useMutation({
    mutationFn: SendSMS,
    onSuccess() {
      startCutDown()
      Toast.success('验证码发送成功')
    },
  })

  return (
    <section
      className="min-h-screen bg-white bg-top bg-no-repeat bg-cover pt-[600px] px-6 pb-4"
      style={{
        'backgroundImage': `url(${Bg})`,
        'backgroundSize': '100% auto',
        '--rv-cell-background-color': '#f3f2f7',
        '--rv-cell-vertical-padding': '16px',
        '--rv-divider-border-color': '#d8d7dc',
        '--rv-field-label-margin-right': 0,
        '--rv-cell-required-color': 'transparent',
      } as React.CSSProperties}
    >

      <Form form={form} onFinish={onFinish} border={false}>
        <Form.Item
          labelWidth={80}
          name="phone"
          style={{
            borderRadius: 8,
          }}
          label={(
            <>
              手机号
              <Divider type="vertical" className="-mr-8 ml-4" />
            </>
          )}
          rules={[{ required: true, message: '请输入手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item
          labelWidth={80}
          name="code"
          className="mt-3"
          style={{
            borderRadius: 8,
          }}
          label={(
            <>
              验证码
              <Divider type="vertical" className="-mr-8 ml-4" />
            </>
          )}

          suffix={(
            <button
              type="button"
              disabled={current.seconds > 0 || isSending}
              className={classNames('text-sm', {
                'text-gray-400': current.seconds > 0,
                'text-primary': current.seconds <= 0,
              })}

              onClick={async () => {
                await form.validateFields(['phone'])
                const phone = form.getFieldValue('phone')
                sendSMS({ phone })
              }}
            >
              {current.seconds > 0 ? `${current.seconds}秒后重发` : '发送验证码'}
            </button>
          )}
          rules={[{ required: true, message: '请输入短信验证码' }]}
        >
          <Input placeholder="请输入短信验证码" maxLength={6} />
        </Form.Item>

        <Checkbox onChange={setAgree} iconSize={16} className="mt-3 mb-4">
          <div className="flex flex-wrap items-center text-xs">
            <span className="text-gray-400">我已阅读并同意以下协议</span>
            <a href="/yonghu.docx">《用户协议》</a>
            <a href="/ys.docx">《隐私协议》</a>
          </div>
        </Checkbox>

        <footer className="pt-12">
          <Button loading={isLogging} nativeType="submit" type="primary" block round>登 录</Button>
          <p className="mt-2 text-xs text-center text-gray-400">未注册的手机号将自动注册</p>
        </footer>
      </Form>
    </section>
  )
}
